package com.tencent.hummingbird.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tencent.hummingbird.portal.pojo.Question;
import com.tencent.hummingbird.portal.pojo.QuestionTag;
import com.tencent.hummingbird.portal.mapper.QuestionTagMapper;
import com.tencent.hummingbird.portal.pojo.Tag;
import com.tencent.hummingbird.portal.service.IQuestionTagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencent.hummingbird.portal.service.ITagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yxb
 * @since 2024-01-10
 */
@Service
public class QuestionTagServiceImpl extends ServiceImpl<QuestionTagMapper, QuestionTag> implements IQuestionTagService {
    @Autowired
    private QuestionTagMapper questionTagMapper;
    @Autowired
    private ITagService tagService;
    @Override
    public PageInfo<Question> getQuestionByTagId(Integer tagId, Integer pageNum, Integer pageSize,String search) {
        PageHelper.startPage(pageNum,pageSize);
        List<Question> questions = new ArrayList<>();
        if(tagId==0){
             questions = questionTagMapper.selectAll();
        }else if(tagId==-1){
            questions = questionTagMapper.searchQuestions(search);
        }
        else {
             questions = questionTagMapper.selectQuestionsByTagId(tagId);
        }

        Map<String, Tag> tagMap = tagService.getNameToTagMap();
        for(Question question : questions){
            String[] tagNames = question.getTagNames().split(",");
            List<Tag> tags = new ArrayList<>();
            for(String tagName : tagNames){
                Tag t = tagMap.get(tagName);
                tags.add(t);
            }
            question.setTags(tags);
        }
        PageInfo<Question> pageInfo = new PageInfo<>(questions);
        return pageInfo;
    }
}
